package com.marketing.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 简单限流过滤器
 * 
 * @author Marketing Team
 * @version 1.0.0
 * @since 2025-09-23
 */
@Component
public class RateLimitFilter implements GlobalFilter, Ordered {

    private static final Logger log = LoggerFactory.getLogger(RateLimitFilter.class);

    // 简单的内存限流器，生产环境建议使用Redis
    private final ConcurrentHashMap<String, AtomicInteger> requestCountMap = new ConcurrentHashMap<>();
    private final int MAX_REQUESTS_PER_MINUTE = 100; // 每分钟最大请求数

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        
        // 获取客户端IP
        String clientIp = getClientIp(request);
        String key = clientIp + ":" + getCurrentMinute();
        
        // 获取当前请求计数
        AtomicInteger requestCount = requestCountMap.computeIfAbsent(key, k -> new AtomicInteger(0));
        int currentCount = requestCount.incrementAndGet();
        
        // 检查是否超过限制
        if (currentCount > MAX_REQUESTS_PER_MINUTE) {
            log.warn("客户端 {} 请求频率过高，当前计数: {}", clientIp, currentCount);
            
            response.setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
            response.getHeaders().add("X-RateLimit-Limit", String.valueOf(MAX_REQUESTS_PER_MINUTE));
            response.getHeaders().add("X-RateLimit-Remaining", "0");
            response.getHeaders().add("X-RateLimit-Reset", String.valueOf(getNextMinute()));
            
            return response.setComplete();
        }
        
        // 添加限流信息到响应头
        response.getHeaders().add("X-RateLimit-Limit", String.valueOf(MAX_REQUESTS_PER_MINUTE));
        response.getHeaders().add("X-RateLimit-Remaining", 
                String.valueOf(MAX_REQUESTS_PER_MINUTE - currentCount));
        response.getHeaders().add("X-RateLimit-Reset", String.valueOf(getNextMinute()));
        
        log.debug("客户端 {} 当前请求计数: {}", clientIp, currentCount);
        
        return chain.filter(exchange);
    }

    /**
     * 获取客户端IP
     */
    private String getClientIp(ServerHttpRequest request) {
        String xForwardedFor = request.getHeaders().getFirst("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty()) {
            return xForwardedFor.split(",")[0].trim();
        }
        
        String xRealIp = request.getHeaders().getFirst("X-Real-IP");
        if (xRealIp != null && !xRealIp.isEmpty()) {
            return xRealIp;
        }
        
        return request.getRemoteAddress() != null ? 
                request.getRemoteAddress().getAddress().getHostAddress() : "unknown";
    }

    /**
     * 获取当前分钟数
     */
    private long getCurrentMinute() {
        return System.currentTimeMillis() / 60000;
    }

    /**
     * 获取下一分钟时间戳
     */
    private long getNextMinute() {
        return (getCurrentMinute() + 1) * 60;
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 1;
    }
}